package helixoide.irc.serverType;
/*
 * Well this class is used to take care of all the stuff related to events and such
 * I think i will make things hook into here so messages and stuff have to go through an unreal3.2 class
 * 
 */
import helixoide.Config;
import helixoide.Util;
import helixoide.hxLog;
import helixoide.otherMain;
import helixoide.secondlife.httpServerMain;
import helixoide.secondlife.devices.*;
import helixoide.users.User;
import helixoide.users.UserManager;
import java.io.*;
public  class unreal32 
{
	private BufferedWriter output;
	private otherMain main = null;
	private UserManager theManagment;
	private deviceManager theOtherManagment;
	private Config serverConfig;
	private boolean acceptedPass;
	public unreal32(BufferedWriter out, Object obj, Config serverConfig)
	{
		acceptedPass = false;
		this.serverConfig = serverConfig;
		output = out;
		main = (otherMain)obj;
		this.theManagment = new UserManager(this);
		this.theOtherManagment = new deviceManager(this.theManagment,this.serverConfig);
		//start the backup loading
		Util.loadDeviceData(theOtherManagment);
		//end of backup loading, we either loaded some backed up devices or none
		httpServerMain theServer = new httpServerMain();
		theServer.init(this.theOtherManagment);
		//we have initialised the http server :D
		
	}
	private synchronized void serverPong() throws IOException
	{
		generalOut("PONG :" + this.serverConfig.getOurURL());//this needs to be made dynamic
	}
	private synchronized void handshake() throws IOException
	{
		generalOut("PASS :" + this.serverConfig.getPasswordConnect());
		generalOut("SERVER " + this.serverConfig.getOurURL() + " 4 :U2309-FiXOoE-1 " + this.serverConfig.getOurName());
		hxLog.write("Protocol System", "initialising, handshake with ircd complete");
		//this handshake will need to be dynamically generated once i make a config class
		
	}
	public synchronized void incomingMessage(String fromIRC)
	{
		/*
		 * This area is kind of confusing so it woudl be best to learn about irc commands more
		 * It should work but since i am writing this at school with no internet access (so i can test
		 * it with irc.helixoide.com) i am not entirely sure how it will work
		 */
		
		//hxLog.write("raw.log","IRC Raw",fromIRC);
		if(fromIRC.startsWith("PASS"))
		{
			String[] passCommand = fromIRC.split(":",2);
			String recievedPass = passCommand[1];
			if(recievedPass.equals(this.serverConfig.getPasswordReceive()))//yay our passwords match!
			{
				System.out.println("SLSERV: INIT: Password Accepted\n");
				this.acceptedPass = true;
			}
			else
			{
				System.out.println("SLSERV: INIT: Password Rejected\n");
			}
		}
		if(this.acceptedPass)
		{
			try
			{
				boolean hasSource = fromIRC.startsWith(":");
				String[] sides = fromIRC.split(":",2);
				boolean hasExtendedArgs =  sides.length > 1;
				String[] tokens = null;
				if(sides.length>1 && sides[1]!=null)
				{
					tokens = sides[1].split(" ",2);
				}
				handle(sides,tokens,hasSource);
				
			}
			catch(Exception e)
			{
				e.printStackTrace();
				main.die();
				System.exit(0);
			}
		}

	}
	private synchronized void handle(String[] stuff,String[] tokens,boolean hasSource)
	{
		try
		{
			if(!hasSource)
			{
				
				if(stuff[0].startsWith("PING"))//the ping statement used to respond
				{
					serverPong();
				}
				if(stuff[0].startsWith("SERVER"))//used to know when the server side of the handshake is over
				{
					handshake();
				}
			}
			if(hasSource)
			{
				/*
				 * 	TOKENS[]
					Posiden
					PRIVMSG #lobby :errg
				 */
				/*
				 * we need to work on this commands
				 * 	Source Posiden command WHOIS SL-Status :SL-Status
				 * 
					:Posiden PRIVMSG SL-Status :PING
					Source Posiden command PRIVMSG SL-Status :PING
					channel SL-Status 
					
					:Posiden PRIVMSG SL-Status :TIME
					Source Posiden command PRIVMSG SL-Status :TIME
					channel SL-Status 
					
					:Posiden PRIVMSG SL-Status :VERSION
					Source Posiden command PRIVMSG SL-Status :VERSION
					channel SL-Status
				 */
				 
				
				String source = tokens[0];
				String command = tokens[1];
				if(command.startsWith("PRIVMSG"))
				{
					
					
					String[] split2 = tokens[1].split(":",2);
					String[] split3 = split2[0].split(" ",2);
					String channel = split3[1];
					
				
					/*
					 * This next section here is an experimental fix to stop sl
					 * serv from eating extra : hopefully it will work the way it is intended
					 */
					String message = "";
					for(int i = 1;i<split2.length;i++)
					{
						message += split2[i];
						if(split2.length>2 && i<split2.length-1)
						{
							message += ":";
						}
					}
					/*
					 * End of super special experimental section
					 */
					if(channel.startsWith("#"))
					{
						
						device[] deviceList = this.theOtherManagment.getDevices();
						device theDevice = null;
						for(int i = 0;i<deviceList.length;i++)
						{
							if(deviceList[i]!=null)
							{
								
								String deviceChan = deviceList[i].getChannel().trim();
								
								if(deviceChan.equalsIgnoreCase(channel.trim()))
								{
									
									theDevice = deviceList[i];
									break;
								}
							}
						}
						if(theDevice!=null)
						{
							theDevice.sayInWorld(source, message);
						}
					}
					if(!channel.startsWith("#"))
					{
						
						User theUser = this.theManagment.findUser(channel.trim());
						if(theUser != null)
						{
							
							if(!theUser.isObject())
							{
								String[] expandedTokens = tokens[1].split(" ",3);
								String query = expandedTokens[2].trim();
								String requester = tokens[0].trim();
								System.out.println(query);
								if(query.trim().indexOf("VERSION") != -1)
								{
									
									hxLog.write("Protocol System", "Sending Version info to " + requester + "\n");
									theUser.privmsg(requester, ":Helixoide SLSERV Second Life IRC Interface System Version 1.5 beta 3");
								}
								else if(query.trim().indexOf("PING") != -1)
								{
									
									hxLog.write("Protocol System", "Sending Pong to " + requester + "\n");
									theUser.privmsg(requester, ":PONG");
								}
								else
								{
									hxLog.write("Protocol System", "Else has been reached");
								}
								
							}
						}
					}
					
				}
				if(command.equalsIgnoreCase("PING"))//the some one is pinging something
				{
					//System.out.println( source + " pinged Soemthing");
					/*
					 * implement a search through all our users
					 * and when we find the right one check if it is still active and return a pong
					 */
				}
				if(command.equalsIgnoreCase("WHOIS"))
				{
					
					//System.out.println(source + "\n" + command + "\n" + otherCommand);
					//theManagment.whoisReply(otherCommand, source);
					//someone wants information about something
					
				}
					
			}
		}
		catch(IOException e)
		{
			e.printStackTrace();
			main.die();
			System.exit(0);
		}
		
	}
	public synchronized void generalOut(String msg)
	{
		
		try
		{
			output.write(msg + "\r\n");
			output.flush();
		}
		catch(IOException e)
		{
			e.printStackTrace();
			main.die();
			System.exit(0);
		}
	}
}
